package com.bosssoft.service_order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Snowflake;
import com.bosssoft.service_order.common.api.CommonPage;
import com.bosssoft.service_order.dao.PortalOrderDao;
import com.bosssoft.service_order.dao.PortalOrderItemDao;
import com.bosssoft.service_order.domain.dto.*;
import com.bosssoft.service_order.domain.po.*;
import com.bosssoft.service_order.mapper.OrderItemMapper;
import com.bosssoft.service_order.mapper.OrderMapper;
import com.bosssoft.service_order.mapper.OrderSettingMapper;
import com.bosssoft.service_order.service.CartItemService;
import com.bosssoft.service_order.service.PortalOrderService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 前台订单管理Service
 */
@Service
public class PortalOrderServiceImpl implements PortalOrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private CartItemService cartItemService;
    @Autowired
    private PortalOrderItemDao orderItemDao;
    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private PortalOrderDao portalOrderDao;
    @Autowired
    private Snowflake snowflake;
    private Long num = Long.valueOf(1);
    private Long num2 = Long.valueOf(1);
    private Long num3 = Long.valueOf(1);

    /**
     * 生成订单
     * @param protalOrderQueryParam
     * @return
     */
    @Override
    public int createOrder(ProtalOrderQueryParam protalOrderQueryParam) {
        Order order = new Order();
        order.setId(snowflake.nextId());
        order.setMemberId(protalOrderQueryParam.getMemberId());
        order.setCouponId(protalOrderQueryParam.getCouponId());
        order.setMemberUsername(protalOrderQueryParam.getMemberUsername());
        order.setDeleteStatus(protalOrderQueryParam.getDeleteStatus());
        order.setTotalAmount(protalOrderQueryParam.getTotalAmount());
        order.setDiscountAmount(protalOrderQueryParam.getDiscountAmount());
        order.setPayAmount(protalOrderQueryParam.getPayAmount());
        order.setFreightAmount(BigDecimal.valueOf(0.00));
        order.setCreateTime(new Date());
        order.setPromotionAmount(BigDecimal.valueOf(0.00));
        order.setIntegrationAmount(BigDecimal.valueOf(0.00));
        order.setCouponAmount(protalOrderQueryParam.getCouponAmount());
        order.setDiscountAmount(BigDecimal.valueOf(0.00));
        order.setDeliveryCompany("顺丰快递");
        order.setDeliverySn(generateDeliverySn());
        order.setIntegration(0);
        order.setReceiveTime(new Date());
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(protalOrderQueryParam.getPayType());
        //订单来源：0->PC订单；1->app订单
        order.setSourceType(0);
        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);
        //订单类型：0->正常订单；1->秒杀订单
        order.setOrderType(0);
        order.setConfirmStatus(0);
        order.setDeleteStatus(0);
        order.setUseIntegration(0);
        //计算赠送积分
        //order.setIntegration(calcGifIntegration(orderItemList));
        //计算赠送成长值
        //order.setGrowth(calcGiftGrowth(orderItemList));
        //生成订单号
        order.setOrderSn(generateOrderSn(order));
        //收货人信息：姓名、电话、邮编、地址
        order.setReceiverName(protalOrderQueryParam.getReceiverName());
        order.setReceiverPhone(protalOrderQueryParam.getReceiverPhone());
        order.setReceiverPostCode(protalOrderQueryParam.getReceiverPostCode());
        order.setReceiverProvince(protalOrderQueryParam.getReceiverProvince());
        order.setReceiverCity(protalOrderQueryParam.getReceiverCity());
        order.setReceiverRegion(protalOrderQueryParam.getReceiverRegion());
        order.setReceiverDetailAddress(protalOrderQueryParam.getReceiverDetailAddress());
        List<OrderSetting> orderSettings = orderSettingMapper.selectByExample(new OrderSettingExample());
        if(CollUtil.isNotEmpty(orderSettings)){
            order.setAutoConfirmDay(orderSettings.get(0).getConfirmOvertime());
        }
        int result = orderMapper.insert(order);
        Long orderId = order.getId();
        List<OrderItem> orderItemList = protalOrderQueryParam.getOrderItemList();

        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderId);
            orderItem.setOrderSn(order.getOrderSn());
            orderItem.setProductId(orderItem.getProductId());
            orderItem.setProductPic(orderItem.getProductPic());
            orderItem.setProductName(orderItem.getProductName());
            orderItem.setProductBrand(orderItem.getProductBrand());
            orderItem.setProductSn(generateProductSn());
            orderItem.setProductPrice(orderItem.getProductPrice());
            orderItem.setProductQuantity(orderItem.getProductQuantity());
            orderItem.setProductSkuId(orderItem.getProductSkuId());
            orderItem.setProductSkuCode(orderItem.getProductSkuCode());
            orderItem.setProductCategoryId(orderItem.getProductCategoryId());
            orderItem.setPromotionName(orderItem.getPromotionName());
            orderItem.setPromotionAmount(orderItem.getPromotionAmount());
            orderItem.setCouponAmount(orderItem.getCouponAmount());
            orderItem.setIntegrationAmount(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(orderItem.getRealAmount());
            orderItem.setGiftIntegration(orderItem.getGiftIntegration());
            orderItem.setGiftGrowth(orderItem.getGiftGrowth());
            orderItem.setProductAttr(orderItem.getProductAttr());
            orderItemMapper.insert(orderItem);
        }
        return result;
    }

    /**
     * 根据订单状态获取订单列表
     * @param uid
     * @param status
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public CommonPage<OrderDetail> list(Long uid, Integer status, Integer pageNum, Integer pageSize) {
        if(status==-1){
            status = null;
        }
        PageHelper.startPage(pageNum,pageSize);
        OrderExample orderExample = new OrderExample();
        OrderExample.Criteria criteria = orderExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0)
                .andMemberIdEqualTo(uid);
        if(status!=null){
            criteria.andStatusEqualTo(status);
        }
        orderExample.setOrderByClause("create_time desc");
        List<Order> orderList = orderMapper.selectByExample(orderExample);
        CommonPage<Order> orderPage = CommonPage.restPage(orderList);
        //设置分页信息
        CommonPage<OrderDetail> resultPage = new CommonPage<>();
        resultPage.setPageNum(orderPage.getPageNum());
        resultPage.setPageSize(orderPage.getPageSize());
        resultPage.setTotal(orderPage.getTotal());
        resultPage.setTotalPage(orderPage.getTotalPage());
        if(CollUtil.isEmpty(orderList)){
            return resultPage;
        }
        //设置数据信息
        List<Long> orderIds = orderList.stream().map(Order::getId).collect(Collectors.toList());
        OrderItemExample orderItemExample = new OrderItemExample();
        orderItemExample.createCriteria().andOrderIdIn(orderIds);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (Order Order : orderList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(Order,orderDetail);
            List<OrderItem> relatedItemList = orderItemList.stream().filter(item -> item.getOrderId().equals(orderDetail.getId())).collect(Collectors.toList());
            orderDetail.setOrderItemList(relatedItemList);
            orderDetailList.add(orderDetail);
        }
        resultPage.setList(orderDetailList);
        return resultPage;
    }

    /**
     * 获取订单商品详情
     * @param orderId
     * @return
     */
    @Override
    public OrderDetail detail(Long orderId) {
        Order Order = orderMapper.selectByPrimaryKey(orderId);
        OrderItemExample example = new OrderItemExample();
        example.createCriteria().andOrderIdEqualTo(orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
        OrderDetail orderDetail = new OrderDetail();
        BeanUtil.copyProperties(Order,orderDetail);
        orderDetail.setOrderItemList(orderItemList);
        return orderDetail;
    }

    /**
     * 订单支付
     * @param orderId
     * @param payType
     * @return
     */
    @Override
    public Integer paySuccess(Long orderId, Integer payType) {
        //修改订单支付状态
        Order order = new Order();
        order.setId(orderId);
        order.setStatus(1);
        order.setPaymentTime(new Date());
        order.setPayType(payType);
        orderMapper.updateByPrimaryKeySelective(order);
        //恢复所有下单商品的锁定库存，扣减真实库存

        OrderDetail orderDetail = portalOrderDao.getDetail(orderId);
        int count = portalOrderDao.updateSkuStock(orderDetail.getOrderItemList());
        return count;
    }

    /**
     * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(Order order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());

        Long increment = num;
        num = num + 1;
        sb.append(date);
        sb.append(String.format("%02d", order.getSourceType()));
        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     * 生成14位订单编号:8位日期+6位以上自增id
     */
    private String generateProductSn() {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        Long increment = num2;
        num2 = num2 + 1;
        sb.append(date);
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     * 生成14位物流编号:8位日期+6位以上自增id
     */
    private String generateDeliverySn() {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        Long increment = num3;
        num3 = num3 + 1;
        sb.append(date);
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }

    /**
     * 计算总金额
     */
    /*private BigDecimal calcTotalAmount(List<OrderItem> orderItemList) {
        BigDecimal totalAmount = new BigDecimal("0");
        for (OrderItem item : orderItemList) {
            totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity())));
        }
        return totalAmount;
    }*/

    /*private void handleRealAmount(List<OrderItem> orderItemList) {
        for (OrderItem orderItem : orderItemList) {
            //原价-促销优惠-优惠券抵扣-积分抵扣
            BigDecimal realAmount = orderItem.getProductPrice()
                    .subtract(orderItem.getPromotionAmount())
                    .subtract(orderItem.getCouponAmount())
                    .subtract(orderItem.getIntegrationAmount());
            orderItem.setRealAmount(realAmount);
        }
    }*/

    /**
     * 计算订单应付金额
     */
    /*private BigDecimal calcPayAmount(Order order) {
        //总金额+运费-促销优惠-优惠券优惠-积分抵扣
        BigDecimal payAmount = order.getTotalAmount()
                .add(order.getFreightAmount())
                .subtract(order.getPromotionAmount())
                .subtract(order.getCouponAmount())
                .subtract(order.getIntegrationAmount());
        return payAmount;
    }*/

    /**
     * 判断下单商品是否都有库存
     */
    /*private boolean hasStock(List<ShoppingTrolley> cartPromotionItemList) {
        for (ShoppingTrolley cartPromotionItem : cartPromotionItemList) {
            if (cartPromotionItem.getRealStock()==null||cartPromotionItem.getRealStock() <= 0) {
                return false;
            }
        }
        return true;
    }*/

    /**
     * 获取订单促销信息
     */
    /*private String getOrderPromotionInfo(List<OrderItem> orderItemList) {
        StringBuilder sb = new StringBuilder();
        for (OrderItem orderItem : orderItemList) {
            sb.append(orderItem.getPromotionName());
            sb.append(";");
        }
        String result = sb.toString();
        if (result.endsWith(";")) {
            result = result.substring(0, result.length() - 1);
        }
        return result;
    }*/

    /**
     * 计算订单优惠券金额
     */
    /*private BigDecimal calcCouponAmount(List<OrderItem> orderItemList) {
        BigDecimal couponAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getCouponAmount() != null) {
                couponAmount = couponAmount.add(orderItem.getCouponAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return couponAmount;
    }*/

    /**
     * 计算订单积分金额
     */
    /*private BigDecimal calcIntegrationAmount(List<OrderItem> orderItemList) {
        BigDecimal integrationAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getIntegrationAmount() != null) {
                integrationAmount = integrationAmount.add(orderItem.getIntegrationAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return integrationAmount;
    }*/

    /**
     * 计算订单活动优惠
     */
    /*private BigDecimal calcPromotionAmount(List<OrderItem> orderItemList) {
        BigDecimal promotionAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            if (orderItem.getPromotionAmount() != null) {
                promotionAmount = promotionAmount.add(orderItem.getPromotionAmount().multiply(new BigDecimal(orderItem.getProductQuantity())));
            }
        }
        return promotionAmount;
    }*/

    /**
     * 计算该订单赠送的积分
     */
    /*private Integer calcGifIntegration(List<OrderItem> orderItemList) {
        int sum = 0;
        for (OrderItem orderItem : orderItemList) {
            sum += orderItem.getGiftIntegration() * orderItem.getProductQuantity();
        }
        return sum;
    }*/

    /**
     * 计算该订单赠送的成长值
     */
    /*private Integer calcGiftGrowth(List<OrderItem> orderItemList) {
        Integer sum = 0;
        for (OrderItem orderItem : orderItemList) {
            sum = sum + orderItem.getGiftGrowth() * orderItem.getProductQuantity();
        }
        return sum;
    }*/

    /**
     * 删除下单商品的购物车信息
     */
    /*private void deleteCartItemList(List<ShoppingTrolley> cartPromotionItemList, Long uid) {
        List<Long> ids = new ArrayList<>();
        for (ShoppingTrolley cartPromotionItem : cartPromotionItemList) {
            ids.add(cartPromotionItem.getGoodId());
        }
        for (Long pid : ids) {
            cartItemService.delete(uid, pid);
        }
    }*/

//    @Override
    /*public void sendDelayMessageCancelOrder(Long orderId) {
        //获取订单超时时间
        OrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
        //发送延迟消息
        cancelOrderSender.sendMessage(orderId, delayTimes);
    }*/

}
